import Cmd from "../data/cmd";
import {SchemaError} from "graphql-tools";

export async function createCmd(args = {}) {
    try {
        let cmd = new Cmd(args.cmd);
        const res = await cmd.save();
        return res;
    } catch (err) {
        console.log(err.message);
        throw new SchemaError(err.message);
    }
}

export async function findCmdList(args = {}) {
  try {
      let { page = 1, pageSize = 10 } = args;
      delete args.page
      delete args.pageSize
      const query = await Cmd.find(args).skip((page - 1) * pageSize).limit(pageSize);
      const total = await Cmd.find(args);
      return {
        page: page,
        pageSize: pageSize,
        list:query,
        totalCount: total.length
      };
  } catch (err) {
      throw new SchemaError(err.message);
  }
}

export async function deleteCmd(_id){
  try {
    const res = await Cmd.findOneAndRemove({_id});
    return res;
  } catch (err) {
      console.log(err);
      throw new SchemaError(err.message);
  }
}

export async function updateCmd(conditions, args){
  try {
    await Cmd.findOneAndUpdate(conditions, args, {
      new: true
    });
    const res = await Cmd.findOne(args)
    return res;
  } catch (err) {
      console.log(err);
      throw new SchemaError(err.message);
  }
}